package com.wy.serivce.impl;

import com.wy.dao.RoomDao;
import com.wy.model.Room;
import com.wy.serivce.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.lang.Nullable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.List;
import java.util.UUID;

/**
 * @描述
 * @创建人 wangyue
 * @创建时间2019/12/216:28
 */
@Service
public class RoomServiceImpl implements RoomService {

    @Value("${mytast.open}")
    public Boolean open;


    @Autowired
    private RoomDao roomDao;

    //条件查询
    @Override
    public Page<Room> pagelist(Room room, int page, int size) {
        Pageable pageable = PageRequest.of(page-1,size);
        Page<Room> pagelist = roomDao.findAll(new Specification<Room>() {
            @Nullable
            @Override
            public Predicate toPredicate(Root<Room> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate pd = criteriaBuilder.conjunction();
                List<Expression<Boolean>> expressions = pd.getExpressions();
                //构建查询条件
                if(room != null){
                    if(room.getCode() != null){
                        expressions.add(criteriaBuilder.like(root.get("code"),"%"+room.getCode()+"%"));
                    }
                    if(room.getState() != null){
                        expressions.add(criteriaBuilder.equal(root.get("state"),room.getState()));
                    }
                }
                return pd;
            }
        }, pageable);
        return pagelist;
    }

    @Override
    public List<Room> getAll() {
        return roomDao.findAll();
    }

    public Room save(Room room) {


        String id=room.getId();
        if(id == null || id.equals("")){
            room.setId(UUID.randomUUID().toString());
        }
        return roomDao.save(room);
    }

    public void delete(String id){
        Room room = new Room();
        room.setId(id);
        roomDao.delete(room);
    }

    public  Room getById(String id){
        return roomDao.getOne(id);
    }

    //定时任务
    //定时执行的方法：不能有返回值、不能有参数
   @Scheduled(cron = "0/3 * * * * ?")
    public void tast1(){
        if(open){
            roomDao.findAll();
            System.out.println("======================");
        }
    }

}